/**
 * 
 */
package com.hndfsj.framework.log;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.util.Log4jWebConfigurer;

/**
 * @author wfq
 * 
 */
public class Log4jConfigListener implements ServletContextListener {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.ServletContextListener#contextInitialized(javax.servlet
	 * .ServletContextEvent)
	 */
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		// TODO Auto-generated method stub
		
		Log4jWebConfigurer.shutdownLogging(event.getServletContext());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seejavax.servlet.ServletContextListener#contextDestroyed(javax.servlet.
	 * ServletContextEvent)
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		ServletContext context = event.getServletContext();
		// 获得context的init参数
		String projectName = context.getInitParameter("projectName");
		String configName = context.getInitParameter("configName");
//		String configType = context.getInitParameter("configType");
	
		System.setProperty("pro", projectName);// 将Log4j日志输出名写入系统,定义变量

		String prefix = context.getRealPath("/");
		prefix = prefix.replaceAll("%20", " ");
		
		System.setProperty("webroot", prefix);// 将应用的root路径写入系统,定义变量
		
		 String log4jRefreshInterval= context.getInitParameter("log4jRefreshInterval");
		 if(StringUtils.isNotBlank(log4jRefreshInterval)){
			 Log4JRefreshInterval.DEFAULT_REFRESHINTERVAL = log4jRefreshInterval;
		 }
		 // logj配置文件路径
		 String log4jLocation= context.getInitParameter("log4jLocation");
		 if(StringUtils.isNotBlank(log4jLocation)){
			 Resource scr=new ServletContextResource(context, log4jLocation);
			 try {
				Log4JRefreshInterval.DEFAULT_LOCATION = scr.getFile().getAbsolutePath();
			} catch (IOException exception) {
			}
		 }else{
				String filePath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
						.replaceAll("%20", " ")
						+ configName + ".xml" ;
			
				//将配置定义为默认配置
				Log4JRefreshInterval.DEFAULT_LOCATION=filePath;

			 
		 }
		 
		Log4JRefreshInterval.initLog4j();
		
	}


}
